<template>
  <div class="activity-log">
    <div
      class="activity-content"
      ref="activityContentRef"
      @scroll="handleScroll"
    >
      <div class="activity-list">
        <div
          v-for="(activity, index) in activityList"
          :key="activity.id"
          class="activity-item"
          :class="{ 'last-item': index === activityList.length - 1 }"
        >
          <div class="activity-avatar">
            <img :src="getUserAvatar(activity)" :alt="getUserName(activity)" />
            <!-- 连接线 -->
            <div
              v-if="index < activityList.length - 1"
              class="avatar-connector"
            ></div>
          </div>

          <div class="activity-details">
            <div class="activity-user">
              <span class="user-name">{{ getUserName(activity) }}</span>
              <span class="activity-time">{{
                formatTime(activity.createTime)
              }}</span>
            </div>

            <div class="activity-content-text">
              {{ getActivityContent(activity) }}
            </div>

            <!-- 如果有标签，显示标签 -->
            <!-- <div v-if="activity.tags && activity.tags.length > 0" class="activity-tags">
              <span 
                v-for="tag in activity.tags" 
                :key="tag"
                class="activity-tag"
                :class="getTagClass(tag)"
              >
                {{ tag }}
              </span>
            </div> -->
          </div>
        </div>
      </div>

      <!-- 加载更多指示器 -->
      <div v-if="loadingMore" class="loading-more">
        <span>加载中...</span>
      </div>

      <!-- 没有更多数据指示器 -->
      <div v-if="!hasMore && activityList.length > 0" class="no-more">
        <span>没有更多动态了</span>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && activityList.length === 0" class="empty-state">
        <span>暂无动态记录</span>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import type { ProjectUpdate } from "@/interface/project";
  import { ref, onMounted, nextTick, watch } from "vue";

  // 定义组件属性
  interface Props {
    projectId?: string;
    logList?: ProjectUpdate[];
  }

  const props = withDefaults(defineProps<Props>(), {
    projectId: "",
    logList: () => [],
  });

  // 响应式数据
  const activityList = ref<ProjectUpdate[]>([]);
  const loading = ref(false);
  const loadingMore = ref(false);
  const hasMore = ref(true);
  const totalCount = ref(0);
  const currentPage = ref(1);
  const pageSize = ref(20);
  const activityContentRef = ref<HTMLElement>();

  // 默认头像
  const defaultAvatar = "/src/assets/default-avatar.png";

  // 滚动处理
  const handleScroll = (event: Event) => {
    const target = event.target as HTMLElement;
    const scrollTop = target.scrollTop;
    const scrollHeight = target.scrollHeight;
    const clientHeight = target.clientHeight;

    if (
      scrollTop + clientHeight >= scrollHeight - 100 &&
      hasMore.value &&
      !loadingMore.value
    ) {
      // loadMoreActivities();
    }
  };

  // 获取用户头像
  const getUserAvatar = (activity: ProjectUpdate) => {
    // 优先使用 creatorName 或 modifierName 生成头像
    const userName = activity.creatorName || activity.modifierName || "User";
    return `https://api.dicebear.com/7.x/avataaars/svg?seed=${userName}`;
  };

  // 获取用户名
  const getUserName = (activity: ProjectUpdate) => {
    return activity.creatorName || activity.modifierName || "未知用户";
  };

  // 获取活动内容
  const getActivityContent = (activity: ProjectUpdate) => {
    // 如果有 actionDetail，尝试解析操作描述
    if (activity.actionDetail) {
      const details = Object.entries(activity.actionDetail);
      if (details.length > 0) {
        return details.map(([key, value]) => `${key}: ${value}`).join(", ");
      }
    }

    // 如果没有具体内容，显示默认信息
    return "更新了项目信息";
  };

  // 格式化时间
  const formatTime = (time: Date | string | undefined) => {
    if (!time) return "";

    const timeObj = time instanceof Date ? time : new Date(time);
    const now = new Date();
    const diff = now.getTime() - timeObj.getTime();

    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (minutes < 1) {
      return "刚刚";
    } else if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 30) {
      return `${days}天前`;
    } else {
      return timeObj.toLocaleDateString("zh-CN");
    }
  };

  // 获取标签样式类
  const getTagClass = (tag: string) => {
    const tagClassMap: Record<string, string> = {
      小程序: "tag-miniprogram",
      首页人口调研: "tag-research",
      专业测试: "tag-test",
      UI视觉设计: "tag-design",
      状态变更: "tag-status",
      时间调整: "tag-time",
      优先级调整: "tag-priority",
      文档更新: "tag-document",
      设计稿: "tag-design",
      bug修复: "tag-bug",
      测试: "tag-test",
      进度更新: "tag-progress",
      代码管理: "tag-code",
      分支创建: "tag-branch",
    };
    return tagClassMap[tag] || "tag-default";
  };

  // 监听 logList 变化
  watch(
    () => props.logList,
    (newLogList) => {
      if (newLogList && newLogList.length > 0) {
        activityList.value = newLogList;
      }
    },
    { immediate: true },
  );

  // 组件挂载时获取数据
  onMounted(() => {
    // 如果有传入的 logList，使用传入的数据
    if (props.logList && props.logList.length > 0) {
      activityList.value = props.logList;
    } else if (props.projectId) {
      // fetchActivities(true);
    }
  });

  // 暴露刷新方法给父组件
  defineExpose({
    // refresh: () => fetchActivities(true)
  });
</script>

<style lang="scss" scoped>
  .activity-log {
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #fff;

    .activity-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px 20px 12px;
      border-bottom: 1px solid #f0f0f0;

      .activity-title {
        font-size: 16px;
        font-weight: 500;
        color: #333;
        margin: 0;
      }

      .activity-count {
        font-size: 14px;
        color: #666;
      }
    }

    .activity-content {
      flex: 1;
      overflow-y: auto;
      // padding: 16px 20px;

      .activity-list {
        .activity-item {
          display: flex;
          padding: 12px 0 0;
          position: relative;

          &:last-child {
            border-bottom: none;
          }

          .activity-avatar {
            position: relative;
            margin-right: 12px;
            display: flex;
            flex-direction: column;
            align-items: center;
            min-height: 64px; // 确保有足够的高度显示连接线

            img {
              width: 24px;
              height: 24px;
              border-radius: 50%;
              object-fit: cover;
              border: 2px solid #fff;
              box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
              position: relative;
              z-index: 2;
            }

            .avatar-connector {
              position: absolute;
              top: 35px;
              left: 50%;
              transform: translateX(-50%);
              width: 1px;
              height: 36px;
              background: linear-gradient(
                to bottom,
                #e8e8e8 0%,
                #e8e8e8 50%,
                transparent 50%,
                transparent 100%
              );
              background-size: 1px 3px;
              background-repeat: repeat-y;
              z-index: 1;
            }
          }

          .activity-details {
            flex: 1;
            min-width: 0; // 防止文本溢出

            .activity-user {
              display: flex;
              align-items: center;
              margin-bottom: 6px;

              .user-name {
                font-size: 13px;
                font-weight: 500;
                color: #333;
                margin-right: 8px;
              }

              .activity-time {
                font-size: 11px;
                color: #999;
              }
            }

            .activity-content-text {
              font-size: 13px;
              color: #666;
              line-height: 1.4;
              margin-bottom: 6px;
              word-wrap: break-word;
            }

            .activity-tags {
              display: flex;
              flex-wrap: wrap;
              gap: 4px;

              .activity-tag {
                display: inline-block;
                padding: 1px 6px;
                border-radius: 10px;
                font-size: 10px;
                line-height: 16px;

                &.tag-miniprogram {
                  background: #e6f7ff;
                  color: #1890ff;
                }

                &.tag-research {
                  background: #f6ffed;
                  color: #52c41a;
                }

                &.tag-test {
                  background: #fff2e8;
                  color: #fa8c16;
                }

                &.tag-design {
                  background: #f9f0ff;
                  color: #722ed1;
                }

                &.tag-default {
                  background: #f5f5f5;
                  color: #666;
                }

                &.tag-status {
                  background: #fff7e6;
                  color: #d46b08;
                }

                &.tag-time {
                  background: #f6ffed;
                  color: #389e0d;
                }

                &.tag-priority {
                  background: #fff1f0;
                  color: #cf1322;
                }

                &.tag-document {
                  background: #f0f5ff;
                  color: #1d39c4;
                }

                &.tag-bug {
                  background: #fff2e8;
                  color: #d4380d;
                }

                &.tag-progress {
                  background: #e6f7ff;
                  color: #0958d9;
                }

                &.tag-code {
                  background: #f9f0ff;
                  color: #531dab;
                }

                &.tag-branch {
                  background: #f6ffed;
                  color: #389e0d;
                }
              }
            }
          }
        }
      }

      .loading-more,
      .no-more,
      .empty-state {
        text-align: center;
        padding: 16px;
        color: #999;
        font-size: 12px;
      }

      .empty-state {
        padding: 40px 20px;
      }
    }
  }

  // 滚动条样式
  .activity-content::-webkit-scrollbar {
    width: 6px;
  }

  .activity-content::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  .activity-content::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;

    &:hover {
      background: #a8a8a8;
    }
  }
</style>
